#coding:utf-8

import time

from flask import Flask
from flask import render_template, request, g, redirect, url_for, session, abort
from flask.ext.login import LoginManager, login_required, login_user, logout_user, current_user

from models import User, Account, SubMessage, WeiHome
from forms import SignupForm, LoginForm, SubMessageForm, AccountForm
from sqlalchemy.sql import and_
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import IntegrityError
from utils.weisdk.basic import check_signature
from utils.dispatcher import dispatcher
from utils.weisdk.parser import parse_user_msg
import hashlib
from utils.weisdk.utils import generate_token

from utils.weisdk.reply import TextReply
from datetime import datetime


from init_db import db_session


app = Flask(__name__)
app.secret_key = 'al+lfjoij1243r7qw9asdf8a@WYHdu!(@*'
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "login"


@login_manager.user_loader
def load_user(user_id):
    return User.query.filter(User.id == user_id).one()


@app.route('/login/', methods=['GET', 'POST',])
def login():
    if request.method == 'POST':
        form = LoginForm(request.form)
        print form.validate()
        if form.validate():
            email = form.email.data
            password = hashlib.md5(form.password.data).hexdigest()
            try:
                user = User.query.filter(User.email == email, User.passwd == password).one()
            except NoResultFound, e:
                return redirect('/login/?error=1')
            login_user(user)
            user.last_login_time = datetime.now()
            db_session.commit()
        return redirect(request.args.get('next') or '/')
    elif request.method == 'GET':
        error = request.args.get('error', None)
    return render_template('login.html', **locals())


@app.route('/logout/')
def logout():
    logout_user()
    return redirect('/')

@app.route('/signup/')
def signup():
    if request.method == 'post':
        form = SignupForm(request.form)
        #if form.validate():
        #    user = User(form.email.data, form.passwd.data)
        #    db_session.add(user)
        #    db_session.commit()
    return render_template('signup.html')

@app.route('/')
@login_required
def index():
    accounts = Account.query.filter(Account.user_id == current_user.id).all()
    #db_session.close()
    if current_user.user_type == 1:
        remain = 10 - len(accounts)
    elif current_user.user_type == 2:
        remain = 2 - len(accounts)
    else:
        remain = 1 - len(accounts)
    return render_template('index.html', **locals())

@app.route('/account/<int:account_id>')
@login_required
def account(account_id):
    account = Account.query.filter(and_(Account.id == account_id, Account.user_id == current_user.id, )).first()
    session['account'] = account.id
    return redirect('/mgaccount/')


@app.route('/mgaccount/')
@login_required
def mg_account():
    panel_title = u"帐号管理"
    is_mgaccount = True
    account = Account.query.filter(Account.id == session['account']).all()

    return render_template('mgaccount.html', **locals())

@app.route('/mgaccount/submsg/', methods=['GET', 'POST'])
@login_required
def mg_submsg():
    panel_title = u'回复管理'
    is_submsg = True
    account_id = session.get('account', None)
    if account_id is None:
        abort(404)
    account = Account.query.get(account_id)
    print account, account.sub_message
    if request.method == 'GET':
        if account.sub_message is None:
            sub_msg_id = 1
        else:
            sub_msg_id = account.sub_message
        sub_message = SubMessage.query.get(sub_msg_id)
        return render_template('mgaccount.html', **locals())
    else:
        form = SubMessageForm(request.form)
        if form.validate():
            if account.sub_message == 1 or account.sub_message is None:
                sub_message = SubMessage()
                sub_message.message = form.sub_message.data
                sub_message.status = 1
                db_session.add(sub_message)
                db_session.flush()
                account.sub_message = sub_message.id
                db_session.commit()
            else:
                sub_message = SubMessage.query.get(account.sub_message)
                sub_message.message = form.sub_message.data
                db_session.commit()


        return ''

@app.route('/mgaccount/weihome/', methods=['GET', 'POST'])
@login_required
def mg_weihome():
    is_weihome = True

    return render_template('mgaccount.html', **locals())

@app.route('/addaccount/', methods=["POST", ])
@login_required
def add_account():
    error = ''
    if current_user.user_type == User.USER_VIP:
        max_account = 10
    elif current_user.user_type == User.USER_NORMAL:
        max_account = 2
    elif current_user.user_type == User.USER_TEST:
        max_account = 1
    else:
        max_account = 0
    user_account = Account.query.filter(Account.user_id == current_user.id).count()
    print user_account
    if user_account <= (max_account - 1):
        form = AccountForm(request.form)
        if form.validate():
            new_account = Account()
            new_account.account = form.name.data
            new_account.user_id = current_user.id
            new_account.add_time = datetime.now()
            new_account.token = generate_token()
            new_account.status = Account.ACCOUNT_NEW
            db_session.add(new_account)
            db_session.commit()
    else:
        error = 'max account 1'
        return error

    return redirect('/')


@app.route('/weihome/<int:account_id>')
def wei_home(account_id):
    account = Account.query.get(account_id)
    wei_home = WeiHome.query.get(account.wei_home)
    return render_template('weihome/tpl_%s.html' % wei_home.template_type, **locals())

################################################
@app.route('/api/<int:account_id>', methods=['GET', 'POST',])
def api(account_id):
    if request.method == 'GET':
        timestamp = request.args['timestamp']
        nonce = request.args['nonce']
        signature = request.args['signature']
        echostr = request.args['echostr']
        account = Account.query.filter(Account.id == account_id).first()
        if not check_signature(account.token, timestamp, nonce, signature):
            return abort(500)

        account.status = Account.ACCOUNT_ADD
        db_session.commit()
        return echostr
    else:
        timestamp = request.args['timestamp']
        nonce = request.args['nonce']
        signature = request.args['signature']
        account = Account.query.filter(Account.id == account_id).first()
        if not check_signature(account.token, timestamp, nonce, signature):
            return abort(500)
        w_message = request.data
        resp = dispatcher(account, w_message)
        return resp




@app.route('/flash/')
def flash():
    db_session.remove()
    return redirect('/')


@app.teardown_appcontext
def shutdown_session(exception=None):
    db_session.remove()


if __name__ == '__main__':
    app.run(debug=True, host="0.0.0.0", port=8080)
